package com.qianfeng.bob.xiexiaobo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.qianfeng.bob.xiexiaobo.fragment.CartContentFragment;
import com.qianfeng.bob.xiexiaobo.fragment.CommunityContentFragment;
import com.qianfeng.bob.xiexiaobo.fragment.HomeContentFragment;
import com.qianfeng.bob.xiexiaobo.fragment.MatchContentFragment;
import com.qianfeng.bob.xiexiaobo.utils.ToastUtils;
import com.qianfeng.bob.xiexiaobo.view.MyCircleImageView;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qzone.QZone;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private static final int REQUEST_CODE  = 1 ;
    /**
     * 这些是主界面下面的一些导航的RadioButton
     */
    private RadioButton mRBHome, mRBMatch, mRBCommunity, mRBCart;
    /**
     * 这些是导航的TextView
     */
    private TextView mTVHome, mTVMatch, mTVCommunity, mTVCart;
    /**
     * 管理fragment的manager
     */
    private FragmentManager mManager;
    /**
     * 主界面当前显示的Fragment
     */
    private SlidingMenu mMenu;
    private Fragment mFragment;
    private HomeContentFragment mHomeContentFragment;
    private MatchContentFragment mMatchContentFragment;
    private CommunityContentFragment mCommunityContentFragment;
    private CartContentFragment mCartContentFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fresco.initialize(this);
        setContentView(R.layout.activity_main);
        initData();
        initView();

    }



    private void initData() {
        ShareSDK.initSDK(this);
        mManager = getSupportFragmentManager();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        // 初始化slidingmenu
        // 添加slidingmenu
        mMenu = new SlidingMenu(this);
        mMenu.setMode(SlidingMenu.RIGHT);
        mMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        mMenu.setTouchModeBehind(SlidingMenu.TOUCHMODE_FULLSCREEN);
        mMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        mMenu.setBehindOffset(150);
        //TODO 添加真正的menu
        mMenu.setMenu(R.layout.sliding_layout);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        FragmentTransaction transaction = mManager.beginTransaction();
        mFragment = new HomeContentFragment();
        transaction.add(R.id.fr_main_content, mFragment).commit();
        //switchContent(null,mFragment);
        mRBHome = (RadioButton) findViewById(R.id.rb_main_home);
        mRBMatch = (RadioButton) findViewById(R.id.rb_main_match);
        mRBCommunity = (RadioButton) findViewById(R.id.rb_main_community);
        mRBCart = (RadioButton) findViewById(R.id.rb_main_cart);
        mTVHome = (TextView) findViewById(R.id.tv_main_home);
        mTVMatch = (TextView) findViewById(R.id.tv_main_match);
        mTVCommunity = (TextView) findViewById(R.id.tv_main_community);
        mTVCart = (TextView) findViewById(R.id.tv_main_cart);
    }

    @Override
    public void onBackPressed() {
        //关闭抽屉
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    public void onClick(View view) {
        if (view == null) return;
        switch (view.getId()) {
            case R.id.rb_main_home:
                if (!(mFragment instanceof HomeContentFragment)) {
                    if (mHomeContentFragment==null){
                        mHomeContentFragment = new HomeContentFragment();
                    }
                    switchContent(mFragment,mHomeContentFragment);
                    mRBMatch.setChecked(false);
                    mRBCommunity.setChecked(false);
                    mRBCart.setChecked(false);
                    mTVHome.setTextColor(getResources().getColor(R.color.text_color_light));
                    mTVMatch.setTextColor(getResources().getColor(R.color.text_color_dark));
                    mTVCommunity.setTextColor(getResources().getColor(R.color.text_color_dark));
                    mTVCart.setTextColor(getResources().getColor(R.color.text_color_dark));
                }

                break;
            case R.id.rb_main_match:
                if (!(mFragment instanceof MatchContentFragment)) {
                     if (mMatchContentFragment==null){
                        mMatchContentFragment = new MatchContentFragment();
                    }
                    switchContent(mFragment,mMatchContentFragment);
                    mRBHome.setChecked(false);
                    mRBCommunity.setChecked(false);
                    mRBCart.setChecked(false);
                    mTVMatch.setTextColor(getResources().getColor(R.color.text_color_light));
                    mTVHome.setTextColor(getResources().getColor(R.color.text_color_dark));
                    mTVCommunity.setTextColor(getResources().getColor(R.color.text_color_dark));
                    mTVCart.setTextColor(getResources().getColor(R.color.text_color_dark));
                }

                break;
            case R.id.rb_main_community:

                if (!(mFragment instanceof CommunityContentFragment)) {
                    if (mCommunityContentFragment == null){
                        mCommunityContentFragment = new CommunityContentFragment();
                    }
                    switchContent(mFragment,mCommunityContentFragment);

                }

                mRBHome.setChecked(false);
                mRBMatch.setChecked(false);
                mRBCart.setChecked(false);
                mTVCommunity.setTextColor(getResources().getColor(R.color.text_color_light));
                mTVHome.setTextColor(getResources().getColor(R.color.text_color_dark));
                mTVMatch.setTextColor(getResources().getColor(R.color.text_color_dark));
                mTVCart.setTextColor(getResources().getColor(R.color.text_color_dark));

                break;
            case R.id.rb_main_cart:

                if (!(mFragment instanceof CartContentFragment)) {
                    if (mCartContentFragment==null){
                        mCartContentFragment = new CartContentFragment();
                    }
                    switchContent(mFragment,mCartContentFragment);


                }
                mRBHome.setChecked(false);
                mRBMatch.setChecked(false);
                mRBCommunity.setChecked(false);

                mTVCart.setTextColor(getResources().getColor(R.color.text_color_light));
                mTVHome.setTextColor(getResources().getColor(R.color.text_color_dark));
                mTVCommunity.setTextColor(getResources().getColor(R.color.text_color_dark));
                mTVMatch.setTextColor(getResources().getColor(R.color.text_color_dark));

                break;
        }
    }

    private static Boolean isExit = false;
    private static Boolean hasTask = false;
    Timer tExit = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            isExit = true;
            hasTask = true;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isExit == false) {
                isExit = true;
                ToastUtils.showShortTimeToast(MainActivity.this, "您真的要退出明星衣橱吗?");

                if (!hasTask) {
                    tExit.schedule(task, 2000);
                }
            } else {
                finish();
                System.exit(0);
            }
        }
        return false;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            startActivityForResult(new Intent(MainActivity.this,TakePictureActivity.class),REQUEST_CODE);
        }
         else if (id == R.id.nav_slideshow) {
            startActivity(new Intent(MainActivity.this,VideoActivity.class));

        }   else if (id == R.id.nav_share) {
             showShare();
        } else if (id == R.id.nav_send) {
            loging();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    private void loging(){
        Platform weibo = ShareSDK.getPlatform(this, SinaWeibo.NAME);

        //weibo.showUser(“3189087725”);//获取账号为“3189087725”的资料
        Platform facebook = ShareSDK.getPlatform(QZone.NAME);
        facebook.SSOSetting(true); // true表示不使用SSO方式授权
        facebook.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                ToastUtils.showLongTimeToast(hashMap.toString(),MainActivity.this);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                ToastUtils.showLongTimeToast("onError",MainActivity.this);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                ToastUtils.showLongTimeToast("onError",MainActivity.this);
            }
        });
        weibo.showUser(null);//执行登录，登录后在回调里面获取用户资料
    }
    private void showShare() {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("愿千锋越来越好，祝老师们身体健康，工作顺利");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        //oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("今天天气真好");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

     // 启动分享GUI
        oks.show(this);
    }
    private void switchContent(Fragment from, Fragment to) {
        if (mFragment != to) {
            mFragment = to;
            FragmentTransaction fragmentTransaction = mManager.beginTransaction();
            if (!to.isAdded()) {    // 先判断是否被add过
                fragmentTransaction.hide(from).add(R.id.fr_main_content, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                fragmentTransaction.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQUEST_CODE&&resultCode== 1&&data!=null){
            byte [] datas = data.getByteArrayExtra("data");
            if (datas!=null&&datas.length>0){
                Bitmap bitmap = BitmapFactory.decodeByteArray(datas,0,datas.length);
                Matrix matrix=new Matrix();
                matrix.setRotate(90);
                //获取新的图片（讲原来的图片旋转90*）
                 bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

                ((MyCircleImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);
            }

        }
    }
}
